package moocloudstudio.minder.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import moocloudstudio.minder.entity.MinderUser;
import moocloudstudio.minder.enums.BooleanEnum;
import moocloudstudio.minder.exception.NotFoundException;
import moocloudstudio.minder.repository.UserRepository;
import moocloudstudio.minder.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;

    @Override
    public String findUsernameAndCheckUserById(String userId) throws Throwable {
        final MinderUser user = userRepository.findById(userId).orElseThrow(() -> new NotFoundException("用户不存在"));
        return user.getUsername();
    }

    @Override
    public MinderUser findUserByUsername(String username) {
        MinderUser queryUser = new MinderUser();
        queryUser.setUsername(username);
        return userRepository.findOne(Example.of(queryUser)).orElse(null);
    }

    @Override
    public MinderUser findAndCheckById(String userId) {
        MinderUser user =  userRepository.findById(userId).orElseThrow(() -> new NotFoundException("用户不存在"));
        if (BooleanEnum.True.getValue().equals(user.getDeleted())){
            throw new RuntimeException("用户已注销");
        }
        return user;
    }

    @Override
    public void checkUserAllowLogin(String userId) {
        MinderUser queryUser = new MinderUser();
        queryUser.setId(userId);
        final MinderUser user = userRepository.findOne(Example.of(queryUser)).orElseThrow(() -> new NotFoundException("用户不存在"));
        if (BooleanEnum.True.getValue().equals(user.getDeleted())){
            throw new RuntimeException("用户已注销");
        }
    }

    @Override
    public void checkUserLogin(String username, String password) {
        final MinderUser user = findUserByUsername(username);
        if (user == null){
            throw new NotFoundException("用户不存在");
        }
        String encryptedPassword = encrypt(password, user.getSalt());
        if (! user.getPassword().equals(encryptedPassword)){
            throw new RuntimeException("账号或密码错误");
        }

        if (BooleanEnum.True.getValue().equals(user.getDeleted())){
            throw new RuntimeException("用户已注销");
        }
    }

    @Override
    public MinderUser register(String username, String password, String nickname) {
        MinderUser resultUser = findUserByUsername(username);
        if (resultUser != null){
            throw new RuntimeException("用户已存在");
        }

        MinderUser user = new MinderUser();
        user.setUsername(username);
        user.setPassword(password);
        user.setNickname(nickname);

        // SHA256盐值加密
        String salt = RandomUtil.randomString(8);
        String result = encrypt(password, salt);
        user.setSalt(salt);
        user.setPassword(result);

        userRepository.save(user);

        return user;
    }

    @Override
    public void deleteById(String userId) {
        userRepository.findById(userId).orElseThrow(() -> new NotFoundException("用户不存在"));
        userRepository.deleteById(userId);
    }

    private String encrypt(String text, String salt){
        Digester digester = new Digester(DigestAlgorithm.SHA256);
        digester.setSalt(salt.getBytes(StandardCharsets.UTF_8));
        return digester.digestHex(text);
    }
}
